package x.ovo.wechat.bot;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import x.ovo.wechat.bot.common.entity.event.MessageEvent;
import x.ovo.wechat.bot.common.entity.message.TextMessage;
import x.ovo.wechat.bot.common.event.Event;
import x.ovo.wechat.bot.common.event.EventListener;

import java.util.Objects;

@Slf4j
@RequiredArgsConstructor
public class WeatherListener extends EventListener<MessageEvent<TextMessage>> {

    private final OkHttpClient client;
    private static final String URL = "https://api.vvhan.com/api/weather?city=";

    @Override
    public boolean support(Event<?> event) {
        return event instanceof MessageEvent
                && event.getSource() instanceof TextMessage
                && ((MessageEvent<?>) event).getContent().contains("天气");
    }

    @Override
    public void onEvent(MessageEvent<TextMessage> event) {
        String userName = event.getSource().getFromUser().getUserName();
        String city = event.getContent().replaceAll("天气", "").trim();

        try {
            Request request = new Request.Builder().url(URL + city).build();
            String string = Objects.requireNonNull(client.newCall(request).execute().body()).string();
            JSONObject object = JSONUtil.parseObj(string);
            String city1 = object.getStr("city");
            JSONObject data = object.getJSONObject("data");
            JSONObject night = data.getJSONObject("night");
            JSONObject air = object.getJSONObject("air");
            String tip = object.getStr("tip");

            String result = data.getStr("date") + " " + data.getStr("week") + "\n" +
                    "[" + city1 + "] " + "今日天气：" +
                    "\n---------------\n" +
                    "天气：" + data.getStr("type") + "\n" +
                    "气温：" + data.getStr("low") + " - " + data.getStr("high") + "\n" +
                    "风向：" + data.getStr("fengxiang") + "\n" +
                    "风力：" + data.getStr("fengli") + "\n" +
                    "夜间：" + night.getStr("type") + " " + night.getStr("fengxiang") + " " + night.getStr("fengli") + "\n" +
                    "空气：" + air.getStr("aqi") + "\n" +
                    "指数：" + air.getStr("aqi_level") + "\n" +
                    "级别：" + air.getStr("aqi_name") + "\n" +
                    "PM2.5：" + air.getStr("pm2.5") +
                    "\n---------------\n" + tip;
            this.context.getApi().sendText(userName, result);
        } catch (Exception ignore) {
            this.context.getApi().sendText(userName, "天气查询失败");
        }
    }
}
